//
//  editMyResumeVoiceResumeCell.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/4/15.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import AVFoundation
import WSProgressHUD
import pop

@objc
protocol editMyResumeVoiceResumeCellDelegate {
    
    //** 开始录音 */
    func startRecord(cell:editMyResumeVoiceResumeCell)
    //** 完成录音 */
    func finishRecord(cell:editMyResumeVoiceResumeCell)
    //** 取消录音 */
    func cancelRecord(cell:editMyResumeVoiceResumeCell)
    
    /** 完成录音文件转换 */
    func sendVoiceData(cell:editMyResumeVoiceResumeCell,data:NSData)
    /** 删除录音 */
    func tapDeleteBtn(cell:editMyResumeVoiceResumeCell)
    
    
    func selectedVoiceBtn(cell:editMyResumeVoiceResumeCell)
    func noSelectVocieBtn(cell:editMyResumeVoiceResumeCell)
    //点击不知道说些什么
    func showHowToSayMyVoiceResume(cell:editMyResumeVoiceResumeCell)
    
}

class editMyResumeVoiceResumeCell: UITableViewCell {
    
    var delegate:editMyResumeVoiceResumeCellDelegate?
    
    var gampView:UIView?
    var headTitle:UILabel?
    var timeLab:UILabel?
    var headerImg:UIImageView?
    var voiceBtn:baseVoiceButton?
    var deleteBtn:UIButton?
    var tapBtn:UIButton?
    var noticeLab:UILabel?
    var voiceBtnPlaceHold:UILabel?
    //录音
    var audioRecorder:Mp3Recorder?
    
    //
    var hub:WSProgressHUD?
    //
    let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),//声音采样率
        AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),//编码格式
        AVNumberOfChannelsKey : NSNumber(int: 1),//采集音轨
        AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue))]//音频质量
    
    var model:editMyResumeVoiceResumeCellModel? {
        
        didSet{
            updateContent(model!)
        }
    }
    //succ
    var recodeSuccessClosure:((data:NSData)->Void)?
    
    var imgH:CGFloat = 40
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setDefaultContent()
        autoLayoutFrame()
        setupMedia()
        
    }
    
    func setupMedia() {
        audioRecorder = Mp3Recorder()
        audioRecorder?.delegate = self
    }
    
    func updateContent(model:editMyResumeVoiceResumeCellModel) {
        
        headTitle?.text = model.voiceTitle
        
        if model.voiceTime.characters.count != 0 {
            timeLab?.text = "\(model.voiceTime)"
            
            let width = DDUtils.boundingRectWithSize(CGSizeMake(400, 20), font: LDFont.Font13, text: model.voiceTime).width + 25
            
            timeLab?.snp_updateConstraints(closure: { (make) in
                
                make.width.equalTo(width)
            })
            
        }
        
        if model.voiceDuration.characters.count != 0 {
            
            voiceBtn?.timeLab?.text = "\(model.voiceDuration)" + "'"
        }
        
        if model.isVoiceContent == true {
            
            voiceBtn?.hidden = false
            voiceBtnPlaceHold?.hidden = true
        } else {
            
            voiceBtn?.hidden = true
            voiceBtnPlaceHold?.hidden = false
        }
    }
    
    func changeStatus() {
        voiceBtn?.hidden = false
        voiceBtnPlaceHold?.hidden = true
    }
    
    func deleteStatus() {
        deleteBtn?.hidden = false
    }
    
    /** 开始录音 */
    
    func startRecodeVoice() {
        
        voiceBtnPlaceHold?.hidden = true
        voiceBtn?.hidden = true
        self.audioRecorder?.startRecord()
        delegate?.startRecord(self)
        hub?.showWithString("正在录音...", maskType: WSProgressHUDMaskType.Default)
    }
    /**  取消录音 */
    func cancelRecordVoice() {
        hub?.dismiss()
        audioRecorder?.cancelRecord()
        delegate?.cancelRecord(self)
    }
    /** 录音结束 */
    func confirmRecordVoice() {
        hub?.dismiss()
        self.delegate?.finishRecord(self)
        self.audioRecorder?.stopRecord()
    }
    
    /**  更新录音显示状态,手指向上滑动后提示松开取消录音 */
    func updateCancelRecordVoice() {
        hub?.showWithString("松开取消录音")
    }
    /** 更新录音状态,手指重新滑动到范围内,提示向上取消录音 */
    func updateContinueRecordVoice() {
        hub?.showWithString("向上滑动取消录音")
    }
    
    //MARK  按钮事件
    
    //开始播放
    func startAnimationPlay() {
        
        let path = NSBundle.mainBundle().URLForResource("voice.gif", withExtension: nil)?.absoluteString as String!
        voiceBtn?.gifView?.image = LDGIFImage.init(contentsOfFile: path)
        voiceBtn?.gifView?.startAnimating()
    }
    
    func sendRecodeVoiceSuccess(fileData:NSData,closure:((data:NSData)->Void)?) {
        if closure != nil {
            recodeSuccessClosure = closure
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
    }
}

extension editMyResumeVoiceResumeCell:Mp3RecorderDelegate{
    
    func failRecord(){
        //        hub?.showErrorWithString("录音失败...")
    }
    
    func beginConvert() {
        
    }
    
    func endConvertWithMP3FileName(fileName: String!) {
        debugPrint(fileName,"-->mp3file")
        
        let voiceData = NSData.init(contentsOfFile: fileName)
        debugPrint(fileName,"-->mp3file","length=\((voiceData?.length)!/1024)K")
        _ = try? NSFileManager.defaultManager().removeItemAtPath(fileName)
        
        hub?.dismiss()
        delegate?.sendVoiceData(self, data: voiceData!)
    }
    
    func setDefaultContent() {
        
        selectionStyle = UITableViewCellSelectionStyle.None
        hub = WSProgressHUD.init(view: self)
        
        gampView = UIView.init()
        gampView?.backgroundColor = LDGolbalColor.White
        backgroundColor = LDGolbalColor.BgGoundGray
        headTitle = UILabel.setDetailsLab("我的亮点", fontSize: 16, titleColor: LDFontColor.Green, Alignment: .Left)
        
        timeLab = UILabel.setDetailsLab("日期", fontSize: 13, titleColor: LDFontColor.White, Alignment: .Center)
        timeLab?.backgroundColor = UIColor.colorWithHexString("#d8d8d8", alapha: 1)
        timeLab?.layer.cornerRadius = 2
        timeLab?.layer.masksToBounds = true
        
        headerImg = UIImageView.init(image: UIImage.init(named: "话筒"))
        voiceBtnPlaceHold = UILabel.setDetailsLab("按住说话即可,长按语音删除", fontSize: 13, titleColor: LDFontColor.LightGray, Alignment: .Left)
        
        //添加点击.长按手势
        voiceBtn = baseVoiceButton()
        voiceBtn?.hidden = true
        voiceBtn?.selected = false
        
        voiceBtn?.bk_whenTapped({ [weak self] in
            
            self?.voiceBtn?.selected = !(self?.voiceBtn!.selected)!
            
            if self?.voiceBtn?.selected == true {
                self?.delegate?.selectedVoiceBtn(self!)
            } else {
                self?.delegate?.noSelectVocieBtn(self!)
            }
            })
        
        let voiceBtntap = UILongPressGestureRecognizer.init(target: self, action: #selector(deleteStatus))
        voiceBtn?.addGestureRecognizer(voiceBtntap)
        
        deleteBtn = UIButton.setDetailsBtn("删除", picName: nil, btnBackColor: nil, titleColor: LDFontColor.White)
        deleteBtn?.hidden = true
        let image = UIImage.init(named: "删除图标")?.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 15, 0, 5), resizingMode: UIImageResizingMode.Stretch)
        deleteBtn?.setBackgroundImage(image, forState:.Normal)
        deleteBtn?.bk_whenTapped({ [weak self] in
            self?.deleteBtn?.hidden = true
            self?.delegate?.tapDeleteBtn(self!)
            })
        
        rac_signalForSelector(#selector(self.touchesBegan(_:withEvent:))).subscribeNext { [weak self] (obj) in
            
            self?.deleteBtn?.hidden = true
        }
        
        tapBtn = UIButton.setDetailsBtn("按住说话", picName: nil
            , btnBackColor: LDGolbalColor.White, titleColor: LDFontColor.DeepBlack)
        
        tapBtn?.setTitle("松开结束", forState: UIControlState.Highlighted)
        tapBtn?.setBackgroundImage(UIImage.setImageWithColor(LDGolbalColor.GreenAssist), forState: UIControlState.Highlighted)
        
        tapBtn?.titleLabel?.font = LDFont.Font15
        tapBtn?.layer.borderWidth = 0.3
        tapBtn?.layer.borderColor = LDFontColor.LightGray.CGColor
        
        
        tapBtn?.addTarget(self, action: #selector(startRecodeVoice), forControlEvents: UIControlEvents.TouchDown)
        tapBtn?.addTarget(self, action: #selector(cancelRecordVoice), forControlEvents: UIControlEvents.TouchUpOutside)
        tapBtn?.addTarget(self, action: #selector(confirmRecordVoice), forControlEvents: UIControlEvents.TouchUpInside)
        tapBtn?.addTarget(self, action: #selector(updateCancelRecordVoice), forControlEvents: UIControlEvents.TouchDragExit)
        tapBtn?.addTarget(self, action: #selector(updateContinueRecordVoice), forControlEvents: UIControlEvents.TouchDragEnter)
        
        
        noticeLab = UILabel.setDetailsLab("不知道说些什么?", fontSize: 14, titleColor: LDFontColor.LightGray, Alignment: .Center)
        noticeLab?.userInteractionEnabled = true
        noticeLab?.bk_whenTapped({ [weak self] in
            
            if self?.delegate != nil && self != nil {
                self?.delegate?.showHowToSayMyVoiceResume(self!)
            }
            })
        
        
        addSubview(gampView!)
        
        gampView!.addSubview(headTitle!)
        gampView!.addSubview(timeLab!)
        gampView!.addSubview(headerImg!)
        gampView!.addSubview(voiceBtn!)
        gampView!.addSubview(deleteBtn!)
        gampView!.addSubview(tapBtn!)
        gampView!.addSubview(noticeLab!)
        gampView?.addSubview(voiceBtnPlaceHold!)
        gampView!.addSubview(hub!)
        
    }
    func autoLayoutFrame() {
        
        gampView?.snp_makeConstraints(closure: { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(LDMargin_H*1)
            make.bottom.equalTo(-LDMargin_H*1)
        })
        headTitle?.snp_makeConstraints(closure: { (make) in
            make.top.equalTo(LDMargin_V*3)
            make.left.equalTo(LDMargin_H*4)
            make.height.equalTo(25)
        })
        timeLab?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo(headTitle!.snp_right).offset(LDMargin_H*2)
            make.centerY.equalTo(headTitle!)
            make.height.equalTo(20)
            make.width.equalTo(25)
        })
        headerImg?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo(headTitle!)
            make.top.equalTo(timeLab!.snp_bottom).offset(LDMargin_H*2)
            make.height.width.equalTo(imgH)
        })
        voiceBtnPlaceHold?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo(headerImg!.snp_right).offset(LDMargin_H*2)//LDMargin_H*4)
            make.centerY.equalTo(headerImg!)
            //            make.width.equalTo(140)
            make.height.equalTo(25)
        })
        voiceBtn?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo(headerImg!.snp_right).offset(LDMargin_H*4)//LDMargin_H*4)
            make.centerY.equalTo(headerImg!)
            make.width.equalTo(140)
            make.height.equalTo(35)//headerImg!)
        })
        deleteBtn?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo((voiceBtn?.snp_right)!).offset(LDMargin_H)
            make.centerY.equalTo(voiceBtn!)
            make.height.equalTo(30)
            make.width.equalTo(70)
        })
        tapBtn?.snp_makeConstraints(closure: { (make) in
            make.top.equalTo((voiceBtn?.snp_bottom)!).offset(LDMargin_H*2)
            make.centerX.equalTo(self)
            make.width.equalTo(200)
            make.height.equalTo(33)
        })
        noticeLab?.snp_makeConstraints(closure: { (make) in
            
            make.centerX.equalTo(tapBtn!)
            make.height.equalTo(15)
            make.bottom.equalTo(-LDMargin_H*2)
        })
    }
}

class editMyResumeVoiceResumeCellModel: NSObject {
    var voiceTitle = String()
    var voiceTime = String()
    var voiceDuration = String()
    var isVoiceContent:Bool = false
    var voiceContentUrl = String()
    var voiceResumeID = String()
}
